package com.xj.demo.controller;

import com.xj.demo.entity.EsBlog;
import com.xj.demo.repository.EsBlogRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p> es-repository </p>
 *
 * @author xujj
 * @description
 * @date 2024/4/14 18:15
 */
@RestController()
@RequestMapping("/repository")
@Api(value = "repository", tags = "repository")
public class EsBlog_RepositoryController {


    private final EsBlogRepository repository;

    public EsBlog_RepositoryController(EsBlogRepository repository) {
        this.repository = repository;
    }

    @PostMapping("/saveBlog")
    @ApiOperation(value = "保存博客", notes = "保存博客")
    public EsBlog save(@RequestBody EsBlog esBlog) {
        return repository.save(esBlog);
    }

    @PostMapping("/saveAllBlog")
    @ApiOperation(value = "批量保存博客", notes = "批量保存博客")
    public void saveAll(@RequestBody List<EsBlog> list) {
        repository.saveAll(list);
    }


    @GetMapping("/deleteBlogById")
    @ApiOperation(value = "通过id删除博客", notes = "通过id删除博客")
    public void deleteBlogById(String id) {
        repository.deleteById(id);
    }


    @PostMapping("/deleteAllBlog")
    @ApiOperation(value = "批量删除博客", notes = "批量删除博客")
    public void deleteAll(@RequestBody List<EsBlog> list) {
        repository.deleteAll(list);
    }

    @GetMapping("/searchById/{id}")
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    public ResponseEntity<EsBlog> searchById(@PathVariable String id) {
        Optional<EsBlog> optional = repository.findById(id);
        return optional.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PostMapping("/searchByIds")
    @ApiOperation(value = "通过id批量查询", notes = "通过id批量查询")
    public List<EsBlog> searchAll(@RequestBody List<String> ids) {
        return (List<EsBlog>)repository.findAllById(ids);
    }

    // 查询所有,并根据id倒序排序
    @GetMapping("/findAll")
    @ApiOperation(value = "查询所有", notes = "查询所有")
    public List<EsBlog> findAll() {
        return (List<EsBlog>)repository.findAll(Sort.by("title").descending());
    }
}
